package cn.com.netedge.iot.frontend.comm.config;

import cn.com.netedge.iot.common.serializer.ByteArrayRedisSerializer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Component;

@Component("feCommRedisConfig")
@RefreshScope
public class RedisConfig {
    @Value("${redis.host}")
    private String host;
    @Value("${redis.port}")
    private int port;
    @Value("${redis.password}")
    private String password;
    @Value("${redis.timeout}")
    private int timeout;

    @Bean("feCommRedisConnectionFactory")
    @Primary
    public RedisConnectionFactory feCommRedisConnectionFactory() {
        RedisStandaloneConfiguration config = new RedisStandaloneConfiguration();
        config.setHostName(host);       // 设置 Redis 主机
        config.setPort(port);                  // 设置 Redis 端口
        config.setPassword(password);   // 设置 Redis 密码

        LettuceConnectionFactory factory = new LettuceConnectionFactory(config);
        // 调用 afterPropertiesSet 方法完成初始化
        factory.afterPropertiesSet();
        return factory;
    }



    @Bean("stringRedisTemplate")
    public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory connectionFactory) {
        StringRedisTemplate template = new StringRedisTemplate(feCommRedisConnectionFactory());
        template.afterPropertiesSet();
        return template;
    }

    @Bean("bytesRedisTemplate")
    public RedisTemplate<String, byte[]> bytesRedisTemplate() {
        RedisTemplate<String, byte[]> template = new RedisTemplate<>();
        template.setConnectionFactory(feCommRedisConnectionFactory());
        // 设置 String 序列化方式
        ByteArrayRedisSerializer byteArraySerializer = new ByteArrayRedisSerializer();
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
        // key 采用 String 序列化
        template.setKeySerializer(stringRedisSerializer);
        // hash 的 key 也采用 String 序列化
        template.setHashKeySerializer(stringRedisSerializer);
        // value 序列化
        template.setValueSerializer(byteArraySerializer);
        // hash value 序列化
        template.setHashValueSerializer(byteArraySerializer);
        template.afterPropertiesSet();
        return template;
    }
}
